﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
//using System.Windows.Forms;

namespace DAL
{
    public class Conect
    {
        SqlCeConnection con = new SqlCeConnection();
        SqlCeTransaction tran;
        string connectstring = @"Data Source=E:\soft\QLCN\QLCN1.sdf";
        public Conect()
        {
            if(connectstring!=null || connectstring!= string.Empty)
                con.ConnectionString = connectstring;
        }

        public void Open() 
        {
            if (con.State == ConnectionState.Closed)
            {
                try
                {
                    con.Open();
                }
                catch (SqlCeException ex)
                { 
                   
                }
            }
                
        }

        public void Close() 
        {
            if (con.State == ConnectionState.Open)
                con.Close();
        }
        public void OpenTran()
        {
            
            
            tran = con.BeginTransaction();
            
        }

        public void ExcuteTran(string str)
        {
            new SqlCeCommand(str, this.con, this.tran).ExecuteNonQuery();
            //tran.Commit();
        }
        public void TranComit()
        {
            tran.Commit();
        }
        public void TranRollback() 
        {
            tran.Rollback();
        }
        public DataTable LoadTable(string sql)
        {
            con.Open();
            SqlCeCommand command = new SqlCeCommand(sql,con);
            SqlCeDataAdapter adapter = new SqlCeDataAdapter(command);
            DataTable tb = new DataTable();
            adapter.Fill(tb);
            con.Close();
            return tb;
        }

        public int UpdateData(string sql)
        {
            con.Open();
            SqlCeCommand command = new SqlCeCommand(sql, con);
            int kq = command.ExecuteNonQuery();
            con.Close();
            return kq;
        }

        public string GetFied(string sql) {
            con.Open();
            SqlCeCommand command = new SqlCeCommand(sql, con);
            SqlCeDataReader reader;
            string kq="";
            reader = command.ExecuteReader();
            while (reader.Read())
            {
                kq = reader.GetString(0).ToString();
            }
            reader.Close();
            con.Close();
            return kq;
        }
    }
}
